package com.android.djlmapp.activity.login;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;

import com.android.djlmapp.BuildConfig;
import com.android.djlmapp.activity.home.HomeActivity;
import com.android.djlmapp.server.RefreshService;
import com.android.djlmapp.server.RefreshTokenTools;
import com.android.djlmapp.tools.global.BasisTimesUtils;
import com.android.djlmapp.tools.global.Constants;
import com.android.djlmapp.tools.global.ConstantsValue;
import com.android.djlmapp.tools.global.PrefUtils;
import com.android.djlmapp.tools.global.UserInfoUtils;
import com.lzy.okgo.OkGo;

import java.util.List;


/**
 * 2017.3.10
 * 张鹏
 * 引导页（刷新token）
 */
public class SplashActivity extends Activity {

    private boolean isLog; // 是否已登录
    private RefreshTokenTools refreshTokenTools;

    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 0:
                    Log.e("项目异常启动", "------启动111------" + BasisTimesUtils.getDeviceTimeOfSSS());
                    // 是否登录
                    isLog = UserInfoUtils.getUserInfoUtilsInstance().getIsLog();
                    String token = UserInfoUtils.getUserInfoUtilsInstance().getToken();
                    Log.e("项目异常", token + "handleMessage:=====是否登录====" + isLog);

                    UserInfoUtils.getUserInfoUtilsInstance().setVerSion(BuildConfig.VERSION_NAME); //保存version

                    if (isLog && !TextUtils.isEmpty(token)) {
                        Log.e("项目异常启动", "------启动222------" + BasisTimesUtils.getDeviceTimeOfSSS());
                        refreshTokenTools = new RefreshTokenTools(SplashActivity.this);
                        refreshTokenTools.setRefreshTokenListener(new RefreshTokenTools.RefreshTokenListener() {
                            @Override
                            public void refreshTokenSuc(String token) {
                                Log.e("项目异常", "------SplashActivity------");
                                UserInfoUtils.getUserInfoUtilsInstance().setToken(token);
                                Log.e("项目异常启动", "------结束启动------" + BasisTimesUtils.getDeviceTimeOfSSS());
                                startActivity(new Intent(SplashActivity.this, HomeActivity.class));
                                finish();
                            }

                            @Override
                            public void refreshTokenFail() {
                                exitLogin();
                            }

                            @Override
                            public void netError() {
//                                exitLogin();
                                startActivity(new Intent(SplashActivity.this, HomeActivity.class));
                                finish();
                            }
                        });
                        refreshTokenTools.refreshServ();
                    } else {
                        // 未登录
                        startActivity(new Intent(SplashActivity.this, LoginActivity.class));
                        finish();
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!isTaskRoot()) {
            finish();
            return;
        }
        initView();
    }

    protected void initView() {
        Log.e("项目异常启动", "------开始启动------" + BasisTimesUtils.getDeviceTimeOfSSS());
        Constants.JPUSH_INTENT = false;
        Constants.APPLICATION_OPEN = true;
    }


    @Override
    protected void onResume() {
        super.onResume();
        mHandler.sendEmptyMessageDelayed(0, 1000);
    }

    private void exitLogin() {
        PrefUtils.putBoolean("isLog", false);
        PrefUtils.putString(ConstantsValue.TOKEN, "");
        Intent intent = new Intent(SplashActivity.this,
                LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK
                | Intent.FLAG_ACTIVITY_NEW_TASK);
        stopService(new Intent(SplashActivity.this, RefreshService.class));

        boolean foreground = isForeground(getApplicationContext(), LoginActivity.class.getName());
        Log.e("项目异常", "------LoginActivity--foreground------" + foreground);
        if (!foreground) {
            startActivity(intent);
            finish();
        }
    }

    /**
     * 判断某个界面是否在前台
     *
     * @param context
     * @param className 某个界面名称
     */
    private boolean isForeground(Context context, String className) {
        if (context == null || TextUtils.isEmpty(className)) {
            return false;
        }

        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            if (className.equals(cpn.getClassName())) {
                return true;
            }
        }

        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkGo.getInstance().cancelAll();
    }
}
